<template>
  <div v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef">
      <FormItem name="mobile" class="enter-x">
        <Input
          size="large"
          v-model:value="formData.mobile"
          :placeholder="t('sys.login.mobile')"
          class="fix-auto-fill"
        />
      </FormItem>
      <FormItem name="sms" class="enter-x">
        <CountdownInput
          size="large"
          class="fix-auto-fill"
          v-model:value="formData.sms"
          :placeholder="t('sys.login.smsCode')"
          :sendCodeApi="handleSendCode"
        />
      </FormItem>

      <FormItem class="enter-x">
        <Button :type="'primary'" size="large" block @click="handleBeforeLogin" :loading="loading">
          {{ t('sys.login.loginButton') }}
        </Button>
        <div id="captcha-div"></div>
        <!--        <Button size="large" block class="mt-4" @click="handleBackLogin">-->
        <!--          {{ t('sys.login.backSignIn') }}-->
        <!--        </Button>-->
      </FormItem>
    </Form>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, computed, unref } from 'vue';
  import { Form, Input, Button } from 'ant-design-vue';
  import { CountdownInput } from '@/components/CountDown';
  import LoginFormTitle from './LoginFormTitle.vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useLoginState, useFormRules, useFormValid, LoginStateEnum } from './useLogin';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import '@/assets/captcha/css/tianai-captcha.css';
  import '@/assets/captcha/js/jquery.min.js';
  import { initRandomCaptcha } from '@/assets/captcha/js/tianai-captcha.js';
  import mcApi from 'mc-c2b2m-operator-api';

  const { SysModule, SystemModule } = mcApi;
  const { UserApi } = SysModule;
  const { QrCodeApi } = SystemModule;

  const props = defineProps({
    appAuthMethod: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const FormItem = Form.Item;
  const { t } = useI18n();
  const { getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);

  const formData = reactive({
    mobile: '',
    sms: '',
  });

  const showAuthBox = ref(false);
  const captcha = ref();
  const { validForm } = useFormValid(formRef);
  const userStore = useUserStore();
  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.MOBILE);
  const { createMessage, notification } = useMessage();

  // 获取图片路径
  function getCaptchaImageUrl(name: string) {
    return new URL(`../../../assets/captcha/images/${name}`, import.meta.url).href;
  }
  // 发送手机验证码
  async function handleSendCode(): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        const form = unref(formRef);
        form.validateFields(['mobile']);
        const authMethodId = props.appAuthMethod.authMethodId;
        if (!authMethodId) {
          createMessage.error('获取登录方式数据失败！');
          resolve(false);
        }
        const model = {
          authFields: [
            {
              key: 'account',
              value: formData.mobile,
            },
          ],
        };
        UserApi.preAuthByAppAuthMethod(model, authMethodId).then(() => {
          resolve(true);
        });
      } catch (_) {
        resolve(false);
      }
    });
  }
  // 滑动验证码
  async function handleBeforeLogin() {
    const data = await validForm();
    if (!data) return;
    showAuthBox.value = true;
    captcha.value = initRandomCaptcha(
      '#captcha-div',
      {
        genCaptchaFun: QrCodeApi.generateSliderCaptcha,
        validCaptchaFun: QrCodeApi.validSliderCaptcha,
        validSuccessCallback: (res: any, c: any) => {
          showAuthBox.value = false;
          c.destroyWindow();
          const { code } = res || {};
          code === 200 ? handleLogin() : createMessage.error('验证失败！');
        },
      },
      {
        btnUrl: getCaptchaImageUrl('move-btn.png'),
        bgUrl: getCaptchaImageUrl('bg-black.jpg'),
        moveTrackMaskBgColor: '#f7b645',
        moveTrackMaskBorderColor: '#ef9c0d',
        // logoUrl: getCaptchaImageUrl('logo.png'),
      },
    );
    captcha.value.loadCaptcha();
  }
  // 登录操作
  async function handleLogin() {
    try {
      loading.value = true;
      const { mobile, sms } = formData;
      const authMethodId = props.appAuthMethod.authMethodId;
      if (!authMethodId) {
        createMessage.error('获取登录方式数据失败！');
        return;
      }
      const model = {
        authFields: [
          {
            key: 'account',
            value: mobile,
          },
          {
            key: 'captcha',
            value: sms,
          },
        ],
      };
      const userInfo = await userStore.login(model, authMethodId);
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.nickName}`,
          duration: 3,
        });
      }
    } catch (e) {
      console.log('e.......', e);
      createMessage.error(e?.message || '登录失败！');
      await userStore.logout();
    } finally {
      loading.value = false;
    }
  }
</script>
